package com.wejoy.video.middle.station.api.controller.common;


import com.wejoy.video.middle.station.api.annotation.LoginCheck;
import com.wejoy.video.middle.station.api.controller.BaseController;
import com.wejoy.video.middle.station.data.enums.file.EnumUpload;
import com.wejoy.video.middle.station.data.exception.BusinessException;
import com.wejoy.video.middle.station.data.service.file.IFileService;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.file.UploadFileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 公共文件上传接口
 *
 * @author: admin
 * @time: 2022/9/20 14:40
 */
@RestController
@RequestMapping("/common/file")
public class UploadAction extends BaseController {
    @Autowired
    private IFileService fileService;

    private static final String FILE_DIRECTORY = "/Users/miracle_j/Desktop/image/";

    @GetMapping(value = "/upload_videosave/{filePath:.+}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseEntity<byte[]> getFile(@PathVariable String filePath) throws IOException {
        File file = new File(FILE_DIRECTORY + File.separator + filePath);
        if (file.exists()) {
            byte[] data = Files.readAllBytes(file.toPath());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("video/mp4"));
            headers.setContentDispositionFormData("inline", file.getName());
            return new ResponseEntity<>(data, headers, HttpStatus.OK);
        } else {
            // 如果文件不存在，返回相应的错误信息
            throw new IOException("File not found: " + filePath);
        }
    }

    @GetMapping("/media/{filename:.+}")
    public ResponseEntity<Resource> viewMedia(@PathVariable String filename) {
        try {
            Path file = Paths.get(FILE_DIRECTORY).resolve(filename).normalize();
            Resource resource = new UrlResource(file.toUri());

            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
    }

    /**
     * 公司文件上传接口
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @LoginCheck
    public RespJSON upload(String uploadItem, @RequestParam("file") MultipartFile file) {
        if (null == file) {
            throw new BusinessException("文件不合法");
        }
        EnumUpload enumUploadItem = EnumUpload.getEnum(uploadItem);
        if (enumUploadItem == null) {
            throw new BusinessException("上传文件类目不正确");
        }
        try {
            Path tempFile = Files.createTempFile("tmp", file.getOriginalFilename());
            file.transferTo(tempFile);
            byte[] bytes = Files.readAllBytes(tempFile);
            UploadFileVO uploadResult = fileService.upload(enumUploadItem, bytes);
            return RespJSON.success(uploadResult);
        } catch (Exception e) {
            logger.error("文件上传错误", e);
            throw new BusinessException("文件上传错误");
        }
    }

    /**
     * 获得上传token
     *
     * @return
     */
    @RequestMapping("/getUploadToken")
    @ResponseBody
    public RespJSON uploadTokenByType() {
        String uploadToken = fileService.getUploadToken();
        return RespJSON.success(uploadToken);
    }
}
